package com.hxkcloud.patient.activitys;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hxkcloud.patient.R;
import com.hxkcloud.patient.YjhApplication;
import com.hxkcloud.patient.beans.AddressBean;
import com.hxkcloud.patient.beans.AddressesBean;
import com.hxkcloud.patient.beans.ArticleKindBean;
import com.hxkcloud.patient.beans.BasicInfoTimeBean;
import com.hxkcloud.patient.beans.DepartmentBean;
import com.hxkcloud.patient.beans.DiseaseBean;
import com.hxkcloud.patient.beans.DiseaseWholeBean;
import com.hxkcloud.patient.beans.HospitalStatusBean;
import com.hxkcloud.patient.beans.LoginInfo;
import com.hxkcloud.patient.beans.MonitorKindBean;
import com.hxkcloud.patient.beans.VersionBean;
import com.hxkcloud.patient.beans.resultbeans.ObjectResultBean;
import com.hxkcloud.patient.dborm.AddressDao;
import com.hxkcloud.patient.dborm.ArticleKindDao;
import com.hxkcloud.patient.dborm.BasicInfoTimeDao;
import com.hxkcloud.patient.dborm.DepartmentDao;
import com.hxkcloud.patient.dborm.DiseaseDao;
import com.hxkcloud.patient.dborm.HospitalStatusDao;
import com.hxkcloud.patient.dborm.LoginInfoDao;
import com.hxkcloud.patient.dborm.MonitorKindDao;
import com.hxkcloud.patient.request.GsonUtils;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.utils.EaseUiUtil;
import com.hxkcloud.patient.utils.SharedPreferenceUtil;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import pub.devrel.easypermissions.EasyPermissions;

public class StartActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    private LinearLayout ll_whole;
    private static final int LOAD_DISPLAY_TIME = 1000;//启动页显示时间

    private List<ArticleKindBean> kinds_news;
    private List<ArticleKindBean> kinds_course;

    private List<BasicInfoTimeBean> basicTimes;

    private int needPrepareNum = 0;//需要获取的基础数据数

    //1个按钮，下载更新
    protected PopupWindow popup_easynotice1;
    private TextView tv_easynotice1_title;
    private TextView tv_easynotice1_func;
    private VersionBean versionBean;
    private String newVersionUrl = "";

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_GETADDRESSLIST_FAIL:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.datagetfail);
                }
                Log.e("basicinfo", "NETWORKCODE_GETADDRESSLIST_FAIL");
                break;
            case MessageCode.NETWORKCODE_GETADDRESSLIST_SUCCESS:
                List<AddressBean> adds = ((AddressesBean) msg.obj).getList();
                AddressDao addressDao = new AddressDao(mContext);
                addressDao.setAddress(adds);
                toLogin();
                break;
            case MessageCode.NETWORKCODE_ARTICLEKINDLIST_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.datagetfail);
                }
                Log.e("basicinfo", "NETWORKCODE_ARTICLEKINDLIST_FAILURE");
                break;
            case MessageCode.NETWORKCODE_HOSPITALSTATUSLIST_SUCCESS:
                List<HospitalStatusBean> hss = (List<HospitalStatusBean>) msg.obj;
                HospitalStatusDao hsDao = new HospitalStatusDao(mContext);
                hsDao.setHospitalStatus(hss);
                toLogin();
                break;
            case MessageCode.NETWORKCODE_HOSPITALSTATUSLIST_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.datagetfail);
                }
                Log.e("basicinfo", "NETWORKCODE_HOSPITALSTATUSLIST_FAILURE");
                break;
            case MessageCode.NETWORKCODE_DEPARTMENTLIST_SUCCESS:
                List<DepartmentBean> dbs = (List<DepartmentBean>) msg.obj;
                DepartmentDao departmentDao = new DepartmentDao(mContext);
                departmentDao.setDepartment(dbs);
                toLogin();
                break;
            case MessageCode.NETWORKCODE_DEPARTMENTLIST_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.datagetfail);
                }
                Log.e("basicinfo", "NETWORKCODE_DEPARTMENTLIST_FAILURE");
                break;
            case MessageCode.NETWORKCODE_DISEASELIST_SUCCESS:
                DiseaseWholeBean ds = (DiseaseWholeBean) msg.obj;
                DiseaseDao diseaseDao = new DiseaseDao(mContext);
                diseaseDao.setDisease(ds);
                toLogin();
                break;
            case MessageCode.NETWORKCODE_DISEASELIST_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.datagetfail);
                }
                Log.e("basicinfo", "NETWORKCODE_DISEASELIST_FAILURE");
                break;
            case MessageCode.NETWORKCODE_ARTICLEKINDLIST_SUCCESS0:
                kinds_news = (List<ArticleKindBean>) msg.obj;
                if (kinds_course != null) {
                    ArticleKindDao kindDao = new ArticleKindDao(mContext);
                    kindDao.setKind(kinds_news, kinds_course, "1");
                    toLogin();
                }
                break;
            case MessageCode.NETWORKCODE_ARTICLEKINDLIST_SUCCESS1:
                kinds_course = (List<ArticleKindBean>) msg.obj;
                if (kinds_news != null) {
                    ArticleKindDao kindDao = new ArticleKindDao(mContext);
                    kindDao.setKind(kinds_news, kinds_course, "1");
                    toLogin();
                }
                break;
            case MessageCode.NETWORKCODE_GETBASICINFOTIMELIST_SUCCESS:
                basicTimes = (List<BasicInfoTimeBean>) msg.obj;
                if (basicTimes != null && basicTimes.size() > 0) {
                    prepareBasic();
                } else {
                    checkBasic();
                }
                break;
            case MessageCode.NETWORKCODE_GETBASICINFOTIMELIST_FAILURE:
                checkBasic();
                Log.e("basicinfo", "NETWORKCODE_GETBASICINFOTIMELIST_FAILURE");
                break;
            case MessageCode.NETWORKCODE_MONITORKIND_SUCCESS:
                List<MonitorKindBean> kinds = (List<MonitorKindBean>) msg.obj;
                if (kinds != null && kinds.size() > 0) {
                    MonitorKindDao monitorKindDao = new MonitorKindDao(mContext);
                    monitorKindDao.setKind(kinds, "1");
                    toLogin();
                }
                break;
            case MessageCode.NETWORKCODE_MONITORKIND_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.datagetfail);
                }
                Log.e("basicinfo", "NETWORKCODE_MONITORKIND_FAILURE");
                break;
            case MessageCode.NETWORKCODE_SUBMITLOGIN_SUCCESS:
                loginInfo = ((ObjectResultBean<LoginInfo>) msg.obj).getData();
                LoginInfoDao userDao = new LoginInfoDao(mContext);
                if (!TextUtils.isEmpty(loginInfo.getAddressId())) {
                    try {
                        String address = "";
                        String addressId = loginInfo.getAddressId();
                        AddressDao addressDaol = new AddressDao(mContext);
                        AddressBean area = addressDaol.getOneAddress(addressId);
                        AddressBean city = addressDaol.getOneAddress(area.getParrentId());
                        AddressBean province = addressDaol.getOneAddress(city.getParrentId());
                        address = province.getName() + city.getName() + area.getName();
                        loginInfo.setAddress(address);
                    } catch (Exception e) {
                    }
                }

                SharedPreferenceUtil.setIsrunning(mContext, true);
                if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_patient)) {
                    userDao.setUser(loginInfo);
                    emClientLogin();
                    JPushInterface.setAlias(mContext, SharedPreferenceUtil.getLoginAccount(mContext), null);
                    //zhugeio
                    try {
                        JSONObject personObject = new JSONObject();
                        personObject.put("name", loginInfo.getName());
                        personObject.put("phone", SharedPreferenceUtil.getLoginAccount(mContext));
                        ZhugeSDK.getInstance().identify(getApplicationContext(), loginInfo.getUserId(),
                                personObject);
                    } catch (JSONException e) {
                    }

                    Intent iPatientMain = new Intent(mContext, UserFragmentActivity.class);
                    iPatientMain.putExtra("getbasic", true);
                    startActivity(iPatientMain);
                    finish();
                } else {
                    Intent iLogin = new Intent(mContext, LoginActivity.class);
                    startActivity(iLogin);
                    finish();
                }
                break;
            case MessageCode.NETWORKCODE_SUBMITLOGIN_FAILURE:
                toastMsg(getResources().getString(R.string.loginfailrelogin));
                Intent iLogin = new Intent(mContext, LoginActivity.class);
                startActivity(iLogin);
                finish();
                break;
            case MessageCode.NETWORKCODE_GETVERSION_SUCCESS:
                if (msg.obj != null) {
                    versionBean = (VersionBean) msg.obj;
                    String localName = SettingActivity.getVersionName(mContext);
                    int i = localName.compareTo(versionBean.getVersion());
                    if (i<0) {
                        tv_easynotice1_title.setText("请更新为最新版本" + versionBean.getVersion());
                        tv_easynotice1_func.setText(R.string.updateversion);
                        newVersionUrl = versionBean.getDownloadUrl();
                        popup_easynotice1.showAtLocation(this.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
                        BrightnessUtils.lightOff(StartActivity.this);
                    }
                    else
                    {
                        // 真正的初始化在更新检测之后
                        initApp();
                    }
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        judgePerssion();
    }

    private static final int REQUEST_CODE_WRITE_SETTINGS = 2;

    //判断23以后的权限
    @TargetApi(23)
    private void judgePerssion() {
        if (Build.VERSION.SDK_INT >= 23) {

            //危险权限
            String[] perms = {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_PHONE_STATE, Manifest.permission.CALL_PHONE, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(this, perms)) {
            } else {
                EasyPermissions.requestPermissions(this, "ddd", 444, perms);
            }

            judgeUpdate();
            //特殊权限
//            if (Settings.System.canWrite(this)) {
//                judgeUpdate();
//            } else {
//                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
//                intent.setData(Uri.parse("package:" + getPackageName()));
//                startActivityForResult(intent, REQUEST_CODE_WRITE_SETTINGS);
//            }
        } else {
            judgeUpdate();
        }
    }

    @TargetApi(23)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_WRITE_SETTINGS) {
            if (Settings.System.canWrite(this)) {
//                toastMsg("权限获取成功");
                Log.i("申请WRITE_SETTINGS权限", "onActivityResult write settings granted");
                judgeUpdate();
            } else {
                toastMsg("权限获取失败");
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        JPushInterface.onResume(mContext);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(mContext);
    }

    /**
     * 更新提示框
     */
    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_easynotice1_func:
                    popup_easynotice1.dismiss();
                    if (!TextUtils.isEmpty(newVersionUrl)) {
                        Uri url = Uri.parse(newVersionUrl);
                        Intent intentUrl = new Intent(Intent.ACTION_VIEW, url);
                        startActivity(intentUrl);

                        SharedPreferenceUtil.setIsrunning(mContext, false);
                        SharedPreferenceUtil.setLoginPassword(mContext, "");
                    } else {
                        toastMsg(R.string.downloadurl_wrong);
                    }
                    break;
            }
        }
    };

    /**
     * 更新检测
     */
    public void judgeUpdate() {
        if (popup_easynotice1 == null) {
            //easynotice
            popup_easynotice1 = new PopupWindow(this);
            View viewNotice = LayoutInflater.from(this).inflate(R.layout.popup_easynotice1, null);
            popup_easynotice1.setContentView(viewNotice);

            popup_easynotice1.setWidth((int) (screenWidth * 0.7));
            popup_easynotice1.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            popup_easynotice1.setFocusable(false);
            popup_easynotice1.setTouchable(true);
            popup_easynotice1.setOutsideTouchable(false);
            popup_easynotice1.setBackgroundDrawable(new ColorDrawable(0x00000000));
            popup_easynotice1.setAnimationStyle(R.style.popupwindow_anim_alpha);

            tv_easynotice1_title = (TextView) viewNotice.findViewById(R.id.tv_easynotice1_title);
            tv_easynotice1_func = (TextView) viewNotice.findViewById(R.id.tv_easynotice1_func);

            tv_easynotice1_title.setText(R.string.current_version_notnew);
            tv_easynotice1_func.setOnClickListener(clickListener);

            popup_easynotice1.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    BrightnessUtils.lightOn(StartActivity.this);
                }
            });
        }

        YiJiaHuNetWorkUtils.getVersion(handler);
    }

    //进入程序流程了
    private void initApp() {
        //非正常退出且处于登录状态，直接进主页
        if (SharedPreferenceUtil.getIsrunning(mContext)) {
            if (loginInfo != null && (!TextUtils.isEmpty(loginInfo.getUserStyle()))) {
                if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_patient)) {
                    emClientLogin();
                    Intent iPatientMain = new Intent(mContext, UserFragmentActivity.class);
                    startActivity(iPatientMain);
                    finish();
                } else {
                    Intent iLogin = new Intent(mContext, LoginActivity.class);
                    startActivity(iLogin);
                    finish();
                }
            } else {
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
                setContentView(R.layout.activity_start);

                initView();

                YiJiaHuNetWorkUtils.getBasicInfoTimeList(handler);
            }
        } else {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            setContentView(R.layout.activity_start);

            initView();

            YiJiaHuNetWorkUtils.getBasicInfoTimeList(handler);

        }

    }

    @Override
    protected void initView() {
        ll_whole = (LinearLayout) findViewById(R.id.ll_start);

        setTitlePadding(ll_whole);
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {

    }

    //根据basicinfotime判断更新
    private void prepareBasic() {
        BasicInfoTimeDao timeDao = new BasicInfoTimeDao(mContext);
        List<BasicInfoTimeBean> localTimes = timeDao.getTime();

        if (localTimes != null && localTimes.size() > 0) {
            needPrepareNum++;
            YiJiaHuNetWorkUtils.getDiseaseList(handler);
            needPrepareNum++;
            YiJiaHuNetWorkUtils.getDepartmentList(handler);
            if (needPrepareNum == 0) {
                handler.postDelayed(new Runnable() {

                    @Override
                    public void run() {

                        login();

                    }
                }, LOAD_DISPLAY_TIME);
            }
        } else {//本地没有times，全部去获取
            toastMsg("正在获取基本数据");
            needPrepareNum = 2;//一共六个
            readLocalArea();
            YiJiaHuNetWorkUtils.getDiseaseList(handler);
            YiJiaHuNetWorkUtils.getDepartmentList(handler);
            //文章类型和监测类别登录后和加入科室接口后再获取
            if ((loginInfo != null) && (!TextUtils.isEmpty(loginInfo.getDepartmentId()))) {
                needPrepareNum = needPrepareNum + 2;
                YiJiaHuNetWorkUtils.getMonitorKind(loginInfo.getDepartmentId(), handler);
                YiJiaHuNetWorkUtils.articleKindList(loginInfo.getDepartmentId(), YjhApplication.articlekind_news, handler);//科室id固定，type两个都取|加入科室后重取
                YiJiaHuNetWorkUtils.articleKindList(loginInfo.getDepartmentId(), YjhApplication.articlekind_course, handler);
            }
        }
        timeDao.setTime(basicTimes);
    }

    private void readLocalArea() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                System.out.println("readLocalAreaStart");
                String content = "";
                InputStream inputStream = null;
                try {
                    inputStream = getResources().openRawResource(R.raw.areas);
                    byte buffer[] = new byte[inputStream.available()];
                    inputStream.read(buffer);
                    content = new String(buffer);
                } catch (IOException e) {
                } finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                        }
                    }
                }
                if (!TextUtils.isEmpty(content)) {
                    ObjectResultBean<AddressesBean> result = GsonUtils.json2Object(content, AddressesBean.class);
                    if (result != null) {
                        if (result.getCode().equals("0")) {
                            List<AddressBean> adds = result.getData().getList();
                            AddressDao addressDao = new AddressDao(mContext);
                            addressDao.setAddress(adds);
                        }
                    }
                }
                System.out.println("readLocalAreaEnd");
            }
        }.start();

    }

    private void toLogin() {
        needPrepareNum--;
        if (needPrepareNum == 0) {
            login();
        }
    }

    private void login() {
        String account = SharedPreferenceUtil.getLoginAccount(mContext);
        String guide = SharedPreferenceUtil.getGuide(mContext);
        if ((!TextUtils.isEmpty(guide)) && guide.equals("T")) {
            if (TextUtils.isEmpty(account)) {
                Intent iLogin = new Intent(mContext, LoginActivity.class);
                startActivity(iLogin);
                finish();
            } else {
                String password = SharedPreferenceUtil.getLoginPassword(mContext);
                if (TextUtils.isEmpty(password)) {
                    Intent iLogin = new Intent(mContext, LoginActivity.class);
                    startActivity(iLogin);
                    finish();
                } else {
                    loading();
                    YiJiaHuNetWorkUtils.submitLogin(account, password, handler);
                }
            }
        } else {
            Intent guideIntent = new Intent(mContext, GuideActivity.class);
            startActivity(guideIntent);
            finish();
        }


    }

    //addressList,department,diseaseList,hospitalStatusList,monitorKind,articleKindList
    //文章类型和监测类别登录后和加入科室接口后再获取
    private String getDate(List<BasicInfoTimeBean> times, String name) {
        String date = "";
        for (BasicInfoTimeBean time : times) {
            if (time.getName().equals(name)) {
                date = time.getDate();
                break;
            }
        }
        return date;
    }

    //失败的话看本地哪个没有就取哪个，都有的话就不管咯
    private void checkBasic() {

        DiseaseDao diseaseDao = new DiseaseDao(mContext);
        List<DiseaseBean> dbs = diseaseDao.getDisease("-1");
        if (dbs == null || dbs.size() == 0) {
            needPrepareNum++;
            YiJiaHuNetWorkUtils.getDiseaseList(handler);
        }

        DepartmentDao departmentDao = new DepartmentDao(mContext);
        List<DepartmentBean> dpbs = departmentDao.getDepartment();
        if (dpbs == null || dpbs.size() == 0) {
            needPrepareNum++;
            YiJiaHuNetWorkUtils.getDepartmentList(handler);
        }

    }

    //环信登录
    private void emClientLogin() {
        String account = SharedPreferenceUtil.getLoginAccount(mContext);
        EMClient.getInstance().login("ejh" + account, "123456", new EMCallBack() {
            @Override
            public void onSuccess() {
                //以下两个方法是为了保证进入主页面后本地会话和群组都 load 完毕
                EMClient.getInstance().chatManager().loadAllConversations();
                EMClient.getInstance().groupManager().loadAllGroups();
                EaseUiUtil.getInstance().init(YjhApplication.getInstance());
                Log.e("EASE", "loginSuccess");
            }

            @Override
            public void onError(int i, String s) {
                Log.e("EASE", "登录聊天服务器失败！" + s);
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.e("easypermission", permissions.length + " permissions result.");
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        //Log.e("easypermission", perms.size() + " permissions granted.");
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        //Log.e("easypermission", perms.size() + " permissions denied.");
    }
}
